use anyhow::{bail, Result};
use clap::Parser;
use std::path::PathBuf;
use yaml_inserter::ProcessResult;

#[derive(Parser)]
#[command(
    name = "yaml-inserter",
    version = "1.0.0",
    about = "A tool to insert multi-line text into YAML files at specified locations."
)]
struct Args {
    /// Input YAML file path
    #[arg(short, long)]
    input: PathBuf,

    /// Output file path (use --in-place to modify input file)
    #[arg(short, long)]
    output: Option<PathBuf>,

    /// Modify the input file in-place
    #[arg(long, conflicts_with = "output")]
    in_place: bool,

    /// Source key name
    #[arg(long, default_value = "conf_source")]
    source_key: String,

    /// Destination key name
    #[arg(long, default_value = "conf_para")]
    dest_key: String,
}

fn main() -> Result<()> {
    let args = Args::parse();

    if !args.in_place && args.output.is_none() {
        bail!("Please specify --output or use --in-place");
    }

    let processor =
        yaml_inserter::YamlProcessor::new(args.source_key.clone(), args.dest_key.clone());

    let result = processor.process_file(&args.input, args.output.as_deref(), args.in_place)?;

    print_summary(&result, &args);

    Ok(())
}

fn print_summary(result: &ProcessResult, args: &Args) {
    if result.total() == 0 {
        println!("No matching keys ('{}') found to process.", args.source_key);
        return;
    }

    println!("Processing complete.");
    if result.processed > 0 {
        let output_target = if args.in_place {
            &args.input
        } else {
            args.output.as_ref().unwrap()
        };
        println!(
            "  - Succeeded: {}. Output written to {}",
            result.processed,
            output_target.display()
        );
    }
    if result.skipped > 0 {
        println!("  - Skipped (source file not found): {}", result.skipped);
    }
    if result.failed > 0 {
        println!("  - Failed (read/security/format error): {}", result.failed);
    }
}
